<template>
  <div>
    <el-input
      v-if="showsearch"
      placeholder="输入关键字进行过滤"
      v-model="filterText"
    >
    </el-input>
    <el-divider v-if="showsearch"></el-divider>
    <el-tree
      class="filter-tree"
      :data="TreeData"
      :node-key="idKey"
      :props="defaultProps"
      default-expand-all
      :filter-node-method="filterNode"
      ref="tree"
      :highlight-current="true"
      :expand-on-click-node="false"
      v-on="$listeners"
      v-bind="$attrs"
    >
    </el-tree>
  </div>
</template>

<script>
export default {
  name: "tree",
  data() {
    return {
      defaultProps: {
        children: "children",
        label: this.nameKey
      },
      filterText: "",
      elTree: {}
    };
  },
  props: {
    data: {
      type: Array,
      default: function() {
        return [];
      }
    },
    idKey: String,
    pIdKey: String,
    nameKey: String,
    showsearch: {
      type: Boolean,
      default: true
    }
  },
  mounted() {},
  updated() {
    this.$nextTick(() => {
      this.elTree = this.$refs.tree;
      this.$emit("onInited", this.$refs.tree);
    });
  },
  methods: {
    /**
     * @description 搜索
     */
    filterNode(value, data) {
      if (!value) return true;
      return data[this.nameKey].includes(value);
    },
    /**
     * @description 节点点击事件
     * @param {Object} data 节点数据对象
     * @param {Object} node 节点对象
     * @param {Object} dom 节点dom
     */
    onNodeClick(data, node, dom) {
      this.$emit("onNodeClick", { data, node, dom });
    }
  },
  computed: {
    //组装Treedata
    TreeData() {
      if (this.data.length == 0) {
        return [];
      }
      let { data, idKey, pIdKey, nameKey } = this;
      let _treedata = [];
      // id: 1,label: '一级 1', children: [{
      let getChildren = item => {
        let thisc = data.search({ [pIdKey]: item[idKey] });
        thisc.forEach(thisc_item => {
          thisc_item.children = getChildren(thisc_item);
        });
        return thisc;
      };
      //得到子菜单
      data.forEach(item => {
        //是否有子
        let c = data.search({ [pIdKey]: item[idKey] });
        if (c.length != 0) {
          item.children = getChildren(item);
          _treedata.push(item);
        }
      });
      return _treedata;
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  }
};
</script>

<style></style>
